import numpy as np
import matplotlib.pyplot as plt

# 中文和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def visualize_geometric_meaning():
    """可视化微分的几何意义"""
    
    # 定义函数和点
    f = lambda x: 0.5*x**3 - x**2 + 2
    x0 = 1.5
    derivative = 1.5*x0**2 - 2*x0  # f'(x) = 1.5x² - 2x
    
    # 生成数据
    x = np.linspace(0.5, 2.5, 100)
    y_curve = f(x)
    y_tangent = f(x0) + derivative * (x - x0)  # 切线方程
    
    # 选择增量
    dx = 0.3
    x1 = x0 + dx
    
    plt.figure(figsize=(12, 10))
    
    # 主图：完整视图
    plt.subplot(2, 1, 1)
    plt.plot(x, y_curve, 'b-', linewidth=3, label='y = f(x)')
    plt.plot(x, y_tangent, 'r--', linewidth=2, label=f'切线 (斜率={derivative:.2f})')
    
    # 标记关键点
    plt.scatter([x0, x1], [f(x0), f(x1)], color='red', s=100, zorder=5)
    plt.scatter([x1], [f(x0) + derivative*dx], color='green', s=100, zorder=5)
    
    # 绘制重要线段
    plt.plot([x0, x1], [f(x0), f(x0)], 'g-', linewidth=2, label='dx = Δx')  # dx
    plt.plot([x1, x1], [f(x0), f(x1)], 'b-', linewidth=2, label='Δy')  # Δy
    plt.plot([x1, x1], [f(x0), f(x0) + derivative*dx], 'r-', linewidth=2, label='dy')  # dy
    
    # 标注点
    plt.annotate(f'P({x0:.1f}, {f(x0):.2f})', (x0, f(x0)), 
                xytext=(x0-0.3, f(x0)-0.4))
    plt.annotate(f'Q({x1:.1f}, {f(x1):.2f})', (x1, f(x1)), 
                xytext=(x1+0.1, f(x1)))
    plt.annotate(f'R({x1:.1f}, {f(x0)+derivative*dx:.2f})', 
                (x1, f(x0)+derivative*dx), xytext=(x1+0.1, f(x0)+derivative*dx-0.3))
    
    plt.title('微分的几何意义：dy是切线的纵坐标改变量')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    # 子图：局部放大
    plt.subplot(2, 1, 2)
    x_zoom = np.linspace(x0-0.2, x0+0.5, 100)
    y_curve_zoom = f(x_zoom)
    y_tangent_zoom = f(x0) + derivative * (x_zoom - x0)
    
    plt.plot(x_zoom, y_curve_zoom, 'b-', linewidth=3, label='f(x)')
    plt.plot(x_zoom, y_tangent_zoom, 'r--', linewidth=2, label='切线')
    
    # 突出显示微分dy
    plt.plot([x0, x1], [f(x0), f(x0) + derivative*dx], 'r-', linewidth=4, alpha=0.6, label='dy')
    plt.fill_between([x0, x1], [f(x0), f(x0)], 
                    [f(x0), f(x0) + derivative*dx], alpha=0.2, color='red')
    
    plt.title('局部放大：微分dy的几何意义')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()
    
    # 数值分析
    print("几何意义数值分析:")
    print(f"点P: ({x0}, {f(x0):.4f})")
    print(f"点Q: ({x1}, {f(x1):.4f})")
    print(f"点R: ({x1}, {f(x0)+derivative*dx:.4f})")
    print(f"Δy = f(x1) - f(x0) = {f(x1)-f(x0):.6f}")
    print(f"dy = f'(x0)·dx = {derivative:.4f} × {dx} = {derivative*dx:.6f}")
    print(f"误差 = Δy - dy = {f(x1)-f(x0)-derivative*dx:.8f}")

visualize_geometric_meaning()